package handler

import (
	"bike-vb/cache"
	"bike-vb/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func PerOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	/*
		SELECT
		  per_son_orders.id AS OrderId,
		  per_sons.per_code AS PerCode,
		  per_sons.per_name AS PerName,
		  per_sons.per_phone AS PerPhone,
		  per_son_orders.order_code AS OrderCode,
		  per_son_orders.order_to AS OrderTO
		FROM
		  per_son_orders
		  LEFT JOIN per_sons ON per_sons.id = per_son_orders.pid
	*/
	var list []model.PerSonOrderList

	redis_key := "per_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("per_son_orders").
			Select(
				"per_son_orders.id AS OrderId",
				"per_sons.per_code AS PerCode",
				"per_sons.per_name AS PerName",
				"per_sons.per_phone AS PerPhone",
				"per_son_orders.order_code AS OrderCode",
				"per_son_orders.order_to AS OrderTO",
			).
			Joins("LEFT JOIN per_sons ON per_sons.id = per_son_orders.pid").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	model.DB.Model(&model.PerSonOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取成功",
		"data":  list,
		"total": total,
	})
}

func PerOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var detail model.PerSonOrderList

	redis_key := "per_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("per_son_orders").
			Select(
				"per_son_orders.id AS OrderId",
				"per_sons.per_code AS PerCode",
				"per_sons.per_name AS PerName",
				"per_sons.per_phone AS PerPhone",
				"per_son_orders.order_code AS OrderCode",
				"per_son_orders.order_to AS OrderTO",
			).
			Joins("LEFT JOIN per_sons ON per_sons.id = per_son_orders.pid").
			Where("per_son_orders.id = ?", id).
			Find(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": detail,
	})
}
